//
//  LoginMainView.m
//  AiShangJinFuSalesman
//
//  Created by AiShangTong on 2017/6/6.
//  Copyright © 2018年 AiShangTong. All rights reserved.
//

#import "LoginMainView.h"


@interface LoginMainView ()

@property (nonatomic, strong) UIButton *logInButton;

@property (nonatomic, strong) NSString *userPhoneNum;
@property (nonatomic, strong) NSString *userPwd;
@property (nonatomic, strong) UILabel *codeNumberLabel;

@end

@implementation LoginMainView

- (instancetype)init {
    
    self = [super init];
    
    if (self) {
        
        [self.numberView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            if (iPhoneX) {
                make.top.mas_equalTo(self.mas_top).offset(260);
            }else if (ScreenWidthMao > 400) {
                make.top.mas_equalTo(self.mas_top).offset(220);
            }else if (ScreenWidthMao > 350) {
                make.top.mas_equalTo(self.mas_top).offset(195);
            }else {
                make.top.mas_equalTo(self.mas_top).offset(150);
            }
            make.left.mas_equalTo(self.mas_left).offset(25);
            make.right.mas_equalTo(self.mas_right).offset(-25);
            make.height.mas_equalTo(50);
        }];
        [self.codeTextView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.mas_equalTo(self.mas_left).offset(25);
            make.right.mas_equalTo(self.mas_right).offset(-25);
            make.top.mas_equalTo(self.numberView.mas_bottom).offset(15);
            make.height.mas_equalTo(50);
        }];
        [self.logInButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.mas_equalTo(self.codeTextView.mas_bottom).offset(40);
            make.left.mas_equalTo(self.mas_left).offset(25);
            make.right.mas_equalTo(self.mas_right).offset(-25);
            make.height.mas_equalTo(48);
        }];
        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        gradientLayer.colors = @[(__bridge id)HexColor(0xD6C096).CGColor, (__bridge id)HexColor(0xBEA471).CGColor];
        gradientLayer.locations = @[@0, @1];
        gradientLayer.startPoint = CGPointMake(0, 1);
        gradientLayer.endPoint = CGPointMake(1, 1);
        gradientLayer.frame = CGRectMake(0, 0, ScreenWidthMao - 50, 48);
        [self.logInButton.layer addSublayer:gradientLayer];
        
        
        UILabel *logInLabel = [[UILabel alloc] init];
        logInLabel.text = @"登录";
        logInLabel.textColor = [UIColor whiteColor];
        logInLabel.font = [UIFont systemFontOfSize:16];
        [logInLabel setTextAlignment:NSTextAlignmentCenter];
        [self.logInButton addSubview:logInLabel];
        
        
        [logInLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.bottom.mas_equalTo(self.logInButton);
        }];
        
       
        
        [self.codeNumberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.numberView.mas_right);
            make.bottom.mas_equalTo(self.logInButton.mas_top).offset(-8);
            make.height.mas_equalTo(15);
        }];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lookUpRegister4)];
        [self.codeNumberLabel addGestureRecognizer:tap];
        
        
        UILabel *bottomLabel = [[UILabel alloc] init];
        bottomLabel.font = [UIFont boldSystemFontOfSize:24];
        bottomLabel.textColor = HexColor(0x333333);
        bottomLabel.text = @"欢迎使用";
        [self addSubview:bottomLabel];
        [bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.mas_left).offset((25));
            if (iPhoneX) {
                make.top.mas_equalTo(self.mas_top).offset(180);
            }else if (ScreenWidthMao > 400) {
                make.top.mas_equalTo(self.mas_top).offset(150);
            }else if (ScreenWidthMao > 350) {
                make.top.mas_equalTo(self.mas_top).offset(90);
            }else {
                make.top.mas_equalTo(self.mas_top).offset(80);
            }
        }];
        
        UILabel *tipLabel = [[UILabel alloc]init];
        tipLabel.font = UIFontMaoNormal;
        tipLabel.textColor = ThemeMaoBackgroundColor;
        tipLabel.text = @"未注册过的手机号将自动创建账号";
        [self addSubview:tipLabel];
        [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(bottomLabel);
            make.top.mas_equalTo(bottomLabel.mas_bottom).offset(10);
            make.height.mas_offset(@15);
        }];
        [self.numberView.writeTextField addTarget:self action:@selector(editingChanged:) forControlEvents:UIControlEventEditingChanged];
        
        self.codeNumberLabel.hidden = YES;
    }
    
    return self;
}

//获取验证码
- (void)getCodeAction:(UIButton *)sender {
    
    self.userPhoneNum = [self restorePhoneNumberWithNumber:self.numberView.writeTextField.text];
    
    if (![HFQCommonTools isValidateMobile:self.userPhoneNum]) {
        
        HFQAnimatedAlert *animatedAlert = [[HFQAnimatedAlert alloc] init];
        [animatedAlert HFQAlert_Style:HFQAlertStyle_Waring accordingDetailContentAutoLayout:@"请输入正确手机号码"];
        [self.numberView.writeTextField becomeFirstResponder];
    }else {
        
        [self.codeTextView.writeTextField becomeFirstResponder];
        NSString *phoneType = [HFQCommonTools deviceModelName];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.userPhoneNum, @"phone", nil];
        if ([self.loginDelegate respondsToSelector:@selector(getVerificationCodeWithDictionary:)]) {
            [self.loginDelegate getVerificationCodeWithDictionary:dic];
        }
        
    }
    
}
- (void)lookUpRegister4 {
    
    self.userPhoneNum = [self restorePhoneNumberWithNumber:self.numberView.writeTextField.text];
    
    if (![HFQCommonTools isValidateMobile:self.userPhoneNum]) {
        
        HFQAnimatedAlert *animatedAlert = [[HFQAnimatedAlert alloc] init];
        [animatedAlert HFQAlert_Style:HFQAlertStyle_Waring accordingDetailContentAutoLayout:@"请输入正确手机号码"];
        [self.numberView.writeTextField becomeFirstResponder];
    }else {
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"接听" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self.codeTextView.writeTextField becomeFirstResponder];
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.userPhoneNum, @"phone", nil];
            if ([self.loginDelegate respondsToSelector:@selector(getVerificationCodeWithDictionary:)]) {
                [self.loginDelegate getVerificationCodeWithDictionary:dic];
            }
            
        }];
        
        UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"语音验证码" message:@"我们将以电话形式告知您验证码, 您可能会接到010、0551、024、029等开头的来电, 请放心接听" preferredStyle:UIAlertControllerStyleAlert];
        
        [ac addAction:action1];
        [ac addAction:action2];
        
        [[HFQCommonTools lastWindow].rootViewController presentViewController:ac animated:YES completion:nil];
        
    }
}

//点击登录按钮事件；
- (void)loginButtonAction:(UIButton *)sender {
    
    self.userPhoneNum = [self restorePhoneNumberWithNumber:self.numberView.writeTextField.text];
    self.userPwd = self.codeTextView.writeTextField.text;
    
    if ([self checkUserLoginInfo]) {
        
        NSString *phoneType = [HFQCommonTools deviceModelName];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.userPhoneNum, @"mobile", self.userPwd, @"code" , @"App", @"channel", phoneType, @"phoneModel", nil];
        [self.loginDelegate loginMainView:dic];
    }
    
}

//对传入数据进行校验
- (BOOL)checkUserLoginInfo {
    
    if (![HFQCommonTools isValidateMobile:self.userPhoneNum]) {
        
        [HUD_Mao showCharacterMessage:@"请填写您的手机号"];
        return NO;
    }
    if (![HFQCommonTools isTrueVerificationCode:self.userPwd]) {
        
        [HUD_Mao showCharacterMessage:@"请输入6位验证码"];
        return NO;
    }
   
    return YES;
}


-(void)setBtnSelect:(BOOL)btnSelect {
    self.codeNumberLabel.hidden = NO;
    if (btnSelect) {
        self.codeNumberLabel.textColor = HexColor(0x999999);
        self.codeNumberLabel.userInteractionEnabled = NO;
    } else {
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"收不到验证码？选择获取语音短信" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]}];
        [attributedString addAttributes:@{NSForegroundColorAttributeName:HexColor(0x999999)} range:NSMakeRange(0, 11)];
        [attributedString addAttributes:@{NSForegroundColorAttributeName:ThemeMaoColor} range:NSMakeRange(11, 4)];
        self.codeNumberLabel.attributedText = attributedString;
        self.codeNumberLabel.userInteractionEnabled = YES;
    }
}

- (textFieldView *)numberView {
    
    if (!_numberView) {
        _numberView = [[textFieldView alloc] init];
        [_numberView.writeTextField setPlaceholder:@"请填写您的手机号"];
        
        [_numberView.writeTextField setValue:HexColor(0xaaaaaa) forKeyPath:@"_placeholderLabel.textColor"];
        [_numberView.writeTextField setValue:[UIFont systemFontOfSize:14]forKeyPath:@"_placeholderLabel.font"];

        [_numberView.writeTextField setBorderStyle:UITextBorderStyleNone];
        [_numberView.writeTextField setKeyboardType:UIKeyboardTypeNumberPad];
        [self addSubview:_numberView];
    }
    return _numberView;
}

- (CodeTextFieldView *)codeTextView {
    
    if (!_codeTextView) {
        _codeTextView = [[CodeTextFieldView alloc] init];
        [_codeTextView.writeTextField setPlaceholder:@"输入验证码"];
        [_codeTextView.writeTextField setValue:HexColor(0xaaaaaa) forKeyPath:@"_placeholderLabel.textColor"];
        [_codeTextView.writeTextField setValue:[UIFont systemFontOfSize:14]forKeyPath:@"_placeholderLabel.font"];
        [_codeTextView.writeTextField setKeyboardType:UIKeyboardTypeNumberPad];
        [_codeTextView.codeButton addTarget:self action:@selector(getCodeAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_codeTextView];
    }
    return _codeTextView;
}
- (UILabel *)codeNumberLabel {
    if (!_codeNumberLabel) {
        _codeNumberLabel = [[UILabel alloc] init];
        [_codeNumberLabel setTextAlignment:NSTextAlignmentLeft];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"收不到验证码？选择获取语音短信" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]}];
        [attributedString addAttributes:@{NSForegroundColorAttributeName:HexColor(0xaaaaaa)} range:NSMakeRange(0, 11)];
        [attributedString addAttributes:@{NSForegroundColorAttributeName:ThemeMaoColor} range:NSMakeRange(11, 4)];
        _codeNumberLabel.attributedText = attributedString;
        _codeNumberLabel.userInteractionEnabled = YES;
        [self addSubview:_codeNumberLabel];
    }
    return _codeNumberLabel;
}
- (UIButton *)logInButton {
    
    if (!_logInButton) {
        
        //添加按钮到BarButton
        _logInButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_logInButton setTitle:@"登录" forState:UIControlStateNormal];
        [_logInButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_logInButton addTarget:self action:@selector(loginButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        _logInButton.layer.cornerRadius = 5;
        _logInButton.layer.masksToBounds = YES;
        _logInButton.titleLabel.font = [Common systemFontOfSize:16];
        [self addSubview:_logInButton];
    }
    return _logInButton;
}

- (void)editingChanged:(UITextField *)textField {
    
    textField.text = [self formattingPhoneNumber:textField.text];
}


//手机号还原
- (NSString *)restorePhoneNumberWithNumber:(NSString *)text {
    
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^•'@#$%^&*()_+'\" - "];
    text = [[text componentsSeparatedByCharactersInSet:set]componentsJoinedByString:@""];
    return text;
}

//标准化 电话号码 111 1111 1111
- (NSString *)formattingPhoneNumber:(NSString *)text {
    
    NSMutableString *mutStr = [text mutableCopy];
    
    if (mutStr.length) {
        
        NSString *passwordStandard = @"^[0-9]+$";
        NSRegularExpression *regexpasswordStandard = [NSRegularExpression regularExpressionWithPattern:passwordStandard options:0 error:nil];
        
        NSTextCheckingResult *isMatchpasswordStandard = [regexpasswordStandard firstMatchInString:mutStr options:0 range:NSMakeRange(mutStr.length-1, 1)];
        
        if (isMatchpasswordStandard) { //符合要求
            
            if ([[text substringWithRange:NSMakeRange(mutStr.length-1, 1)] isEqualToString:@" "]) {
                [mutStr deleteCharactersInRange:NSMakeRange(mutStr.length-1, 1)];
            }else {
                if (text.length > 3 && ![[text substringWithRange:NSMakeRange(3, 1)] isEqualToString:@" "]) {
                    [mutStr insertString:@" " atIndex:3];
                }
                if (text.length > 8 && ![[text substringWithRange:NSMakeRange(8, 1)] isEqualToString:@" "]) {
                    [mutStr insertString:@" " atIndex:8];
                }
            }
            
            text = mutStr;
            
        }else {
            text = [text substringToIndex:mutStr.length - 1];
        }
    }
    
    if (text.length > 13) {
        
        text = [text substringToIndex:13];
    }
    
    return text;
}

@end
